package com.hs.communication.common.encrypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 如果通信过程中需要非对称加密,可以引用此类实现
 */
public class RSAEncrypt {

    private static final String message = "hs-will-be-better";
    public static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqOAhpj/n3k35ZhG9GkRvVLJUd25jxLRJdt7l2FSZO0Wul9QpZMwdEJpMCJWpA5Cq35tikZCBP302QcWYdgBkahD+2fu0sZn657uAp/AQm+eXMCrOb/uxXq9Dcst8JzC6fxUnlh2oGwTl4F96il9o/QXMlh4IJU740dCqp8WwyipHkFqk4Gmo3NAFF5tUgIo/M335st8eUZRgyBSUWo3HOhWDSd6xo9G0DZtlgAdDfucCVycGBc4uMZeraziYQBPrR7tOToqSFta/JF2TIDcqqaDvZ6i99WoXvueXzH1gqAT1QWeMGdCwT14zbQ/eQKcFXKizRJFLXgIyvD9Ul3ADzQIDAQAB";
    private static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCo4CGmP+feTflmEb0aRG9UslR3bmPEtEl23uXYVJk7Ra6X1ClkzB0QmkwIlakDkKrfm2KRkIE/fTZBxZh2AGRqEP7Z+7Sxmfrnu4Cn8BCb55cwKs5v+7Fer0Nyy3wnMLp/FSeWHagbBOXgX3qKX2j9BcyWHgglTvjR0KqnxbDKKkeQWqTgaajc0AUXm1SAij8zffmy3x5RlGDIFJRajcc6FYNJ3rGj0bQNm2WAB0N+5wJXJwYFzi4xl6trOJhAE+tHu05OipIW1r8kXZMgNyqpoO9nqL31ahe+55fMfWCoBPVBZ4wZ0LBPXjNtD95ApwVcqLNEkUteAjK8P1SXcAPNAgMBAAECggEAQgEwRblul/3j/5fpUG31EaaNywxTZFuO5y4hqdcO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mGO22HJ37lEZiy6TohKoAd8xe5oSV4fqWfxlWv0Jx2WZuacrMXPk2RBV5xBUGNzJc66foIFLBkH0/JpjiEabE8V3smZhDi9mqf0=";

    public static void main(String[] args) throws Exception {
        //生成公钥和私钥
//        genKeyPair();
        //加密字符串

//        System.out.println("随机生成的公钥为:" + publicKeyString);
//        System.out.println("随机生成的私钥为:" + privateKeyString);
//        String messageEn = encrypt(message);
//        System.out.println(message + "\t加密后的字符串为:" + messageEn);
//        String messageDe = decrypt(messageEn);
//        System.out.println("还原后的字符串为:" + messageDe);
    }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(2048, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
    }

    /**
     * RSA公钥加密
     *
     * @param msg 加密字符串
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static byte[] encrypt(byte[] msg) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] bytes = cipher.doFinal(msg);
//        String outStr = Base64.encodeBase64String(cipher.doFinal(msg));
        return bytes;
    }

    /**
     * RSA私钥解密
     *
     * @param msg 加密字符串
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static byte[] decrypt(byte[] msg) {
        try {
            //64位解码加密后的字符串
//        byte[] inputByte = Base64.decodeBase64(msg);
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] bytes = cipher.doFinal(msg);
//        String outStr = new String(cipher.doFinal(inputByte));
            return bytes;
        } catch (Exception e) {
            System.out.println("RSA解密异常---返回原文");
            e.printStackTrace();
            return msg;
        }
    }
}

